<?php

namespace app\controllers\api;

use app\models\Material;
use app\models\News;
use app\models\User;
use app\models\UserMaterial;
use app\models\UserProduct;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class MaterialController extends BaseController {
    public function actionList($name = '') {
        $user = $this->check();
        $models = Material::find()
            ->andFilterWhere([
                'name' => $name,
            ])
//            ->andWhere([
//                'country_id' => $user->country_id,
//            ])
            ->all();
        $this->log('原料 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }

    public function actionUserList($name = '') {
        $user = $this->check();
        $models = UserMaterial::find()
            ->andFilterWhere([
                'name' => $name,
            ])
            ->andWhere([
                'user_id' => $user->id,
            ])
            ->all();
        $this->log('原料 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }

    public function actionBuy() {
        $user = $this->check();
        $this->checkModify();
        $material_id = Yii::$app->request->post('material_id');
        $num = Yii::$app->request->post('num');
        /** @var Material $material */
        $material = Material::findOne($material_id);
        if(!$material || $material->country_id != $user->country_id) {
            throw new UserException('选择原料不存在');
        }
        if($material->level > $user->material_level) {
            throw new UserException('等级不足，无法购买');
        }
        /** @var UserMaterial $userMaterial */
        $userMaterial = UserMaterial::getByMaterial($material, $user);
        if($num<0) {
            throw new UserException('购买数量错误');
        }
        if($num>$material->inventory) {
            throw new UserException('购买数量超过剩余库存');
        }
        $userMaterial->storage_num += $num;
        $material->inventory-=$num;

        $this->transaction(function() use ($userMaterial, $material, $user, $num) {
            $userMaterial->save();
            $material->save();
            $this->log('原料 - 购买', $userMaterial->id, -$material->price * $num);
            $this->logForUser(User::findOne(['role'=>'4']), '原料-出售', '', $material->price * $num);
        });

        return $this->renderSuccess([
            'userMaterial' => $userMaterial,
        ]);
    }
}
